package jp.seraph.jsade.model;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import jp.seraph.jsade.math.Point3D;

import org.apache.commons.math.geometry.Vector3D;

/**
 * ObjectCollectionのデフォルト実装です。
 * 
 * 
 */
public class DefaultObjectCollection implements ObjectCollection {
    public DefaultObjectCollection(ModelObject... aObjects) {
        mObjects = new ArrayList<ModelObject>(aObjects.length);
        for (ModelObject tObj : aObjects)
            mObjects.add(tObj);
    }

    public void add(ModelObject aObject) {
        mObjects.add(aObject);
    }

    public void remove(ModelObject aObject) {
        mObjects.remove(aObject);
    }

    private List<ModelObject> mObjects;

    public ModelObject getObject(String aName) {
        for (ModelObject tObj : mObjects) {
            if (tObj.getName().equals(aName))
                return tObj;
        }

        return null;
    }

    public int getObjectCount() {
        return mObjects.size();
    }

    public ModelObject getObject(int aIndex) {
        return mObjects.get(aIndex);
    }

    /**
     * オブジェクト群の平均座標を返す。
     */
    public Point3D getAbsoluteCoordinate() {
        if (this.getObjectCount() == 0)
            return Point3D.origin;

        double tX = 0;
        double tY = 0;
        double tZ = 0;

        for (ModelObject tObj : mObjects) {
            Point3D tPoint = tObj.getAbsoluteCoordinate();
            tX = tPoint.getX();
            tY = tPoint.getY();
            tZ = tPoint.getZ();
        }

        int tCount = this.getObjectCount();
        return new Point3D(tX / tCount, tY / tCount, tZ / tCount);
    }

    /**
     * このオブジェクト群の重心を返す
     */
    public Point3D getCentorOfGravity() {
        if (this.getObjectCount() == 0)
            return Point3D.origin;

        Vector3D tTotalVector = Vector3D.zero;
        double tTotalMass = 0;

        for (ModelObject tObj : mObjects) {
            tTotalVector = tTotalVector.add(tObj.getMass(), tObj.getCentorOfGravity().getVector());
            tTotalMass += tObj.getMass();
        }

        return new Point3D(tTotalVector.scalarMultiply(1.0 / tTotalMass));
    }

    /**
     * このオブジェクト群の質量の合計を取得する。
     */
    public double getMass() {
        double tResult = 0;
        for (ModelObject tObj : mObjects) {
            tResult += tObj.getMass();
        }

        return tResult;
    }

    public String getName() {
        StringBuilder tBuilder = new StringBuilder();

        for (ModelObject tObj : mObjects) {
            tBuilder.append(tObj.getName());
        }

        return tBuilder.toString();
    }

    /**
     * 
     * @see java.lang.Iterable#iterator()
     */

    public Iterator<ModelObject> iterator() {
        return mObjects.iterator();
    }

}